import 'dart:async';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:freedom/const/app_content.dart';
import 'package:freedom/const/game_const.dart';
import 'package:freedom/entity/restful.dart';
import 'package:freedom/entity/user_entity_info.dart';
import 'package:freedom/entity/bottom_item.dart';
import 'package:freedom/page/user_login_widget.dart';
import 'package:freedom/util/api_router.dart';
import 'package:freedom/util/customer_dialog.dart';
import 'package:freedom/util/insert_home.dart';
import 'package:freedom/util/cache_util.dart';
import 'package:freedom/util/http.dart';
import 'package:freedom/util/navigator_provider.dart';
import 'package:freedom/util/path_clipper.dart';
import 'package:freedom/webrtc/mircophone_open.dart';
import 'package:freedom/widget/bubble_widget.dart';
import 'package:freedom/widget/dialog/add_home_dialog.dart';
import 'package:freedom/widget/dialog/create_home_dialog.dart';
import 'package:freedom/page/mahjong/dialog/hoom_record_history_dialog.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import '../widget/mahjong_common.dart';

class GameIndex extends StatefulWidget {
  final bool autoAddHome;
  const GameIndex({super.key, this.autoAddHome = true});
  @override
  GameIndexState createState() => GameIndexState();
}

class GameIndexState extends State<GameIndex> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  void _handlerDrawerButton() {
    _scaffoldKey.currentState!.openEndDrawer();
  }

  void _showRecord() {
    CustomerDialog.showGamingDialog(
        (cancelFunc) => HoomRecordHistoryDialog(cancelFunc));
  }

  void _loginOut() {
    CacheUtil.preferencesInstance!.remove(CacheConst.userInfo);
    NavigatorProvider.pushAndRemoveUntil(UserLoginWidget());
  }

  void _appInfo() async {
    String url = "${ApiRouter.getHttpServer()}open/api/app/dowinfo";
    if (await canLaunchUrl(Uri.parse(url))) {
      await launchUrl(Uri.parse(url));
    } else {
      throw '无法打开 $url';
    }
  }

  // 底部菜单
  List<BottomItem> _bottomItemList = [];

  // 侧拉菜单
  List<BottomItem>? _drawItemList;
  final ScrollController _scrollController = ScrollController();

  DateTime endTime = DateTime.now();

  Timer? scrollTimer;

  @override
  void initState() {
    super.initState();
    MircoPhoneOpen().exitVoiceRoom();
    // 同步加载 麻将资源资源
    _bottomItemList = [
      BottomItem.init(
          icon: Icons.car_rental,
          name: '战绩',
          action: _showRecord,
          image: "assets/images/system/history.png"),
      BottomItem.init(
          icon: Icons.menu,
          name: '菜单',
          action: _handlerDrawerButton,
          image: "assets/images/system/menu.png")
    ];
    _drawItemList = [
      BottomItem.init(icon: Icons.exit_to_app, name: '退出', action: _loginOut),
      BottomItem.init(icon: Icons.info_rounded, name: '版本信息', action: _appInfo),
    ];
    _scrollController.addListener(() {
      endTime = DateTime.now();
      if (_scrollController.offset ==
          _scrollController.position.maxScrollExtent) {
        _scrollController.animateTo(0,
            duration: const Duration(seconds: 20), curve: Curves.easeOut);
      } else if (_scrollController.offset == 0) {
        _scrollController.animateTo(_scrollController.position.maxScrollExtent,
            duration: const Duration(seconds: 20), curve: Curves.easeOut);
      }
    });

    WidgetsBinding.instance.addPostFrameCallback((con) {
      if (widget.autoAddHome) {
        Future.delayed(const Duration(seconds: 1), () {
          // 检查用户是否在房间内
          Http.getInstance().request<Restful>(ApiRouter.getRoom,
              showErrorMsg: true, success: (data) {
            if (data.body != null) {
              Map roomInfo = data.body as Map;
              InsertHome.addHome(context, roomInfo["type"], roomInfo["code"]);
            }
          });
        });
      }
      textToEnd();
      scrollTimer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
        DateTime currentTime = DateTime.now();
        Duration difference = currentTime.difference(endTime);
        if (difference.inSeconds > 2) {
          textToEnd();
        }
      });
    });
  }

  void textToEnd() {
    _scrollController.animateTo(
      _scrollController.position.maxScrollExtent,
      duration: const Duration(seconds: 20),
      curve: Curves.easeOut,
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    scrollTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      endDrawer: Container(
        decoration: const BoxDecoration(
            gradient: LinearGradient(
                begin: Alignment.centerRight,
                end: Alignment.centerLeft,
                stops: [
              0.0,
              1.0
            ], //[渐变起始点, 渐变结束点]
                //渐变颜色[始点颜色, 结束颜色]
                colors: [
              Color.fromARGB(255, 0, 0, 0),
              Color.fromARGB(20, 36, 41, 46)
            ])),
        child: Row(
          children: [
            Expanded(
                child: InkWell(
                    onTap: () {
                      _scaffoldKey.currentState!.closeEndDrawer();
                    },
                    child: const SizedBox(
                      width: double.infinity,
                      height: double.infinity,
                    ))),
            SizedBox(
              width: 40.h * 4,
              child: ListView(
                  children: _drawItemList!
                      .map((ditem) => MaterialButton(
                            onPressed: ditem.action,
                            child: Container(
                                height: 40.h,
                                width: 40.h * 4,
                                decoration: const BoxDecoration(
                                    border: Border(
                                        bottom: BorderSide(
                                            width: 2,
                                            color: Color.fromARGB(
                                                28, 158, 158, 158)))),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Icon(
                                      ditem.icon,
                                      color: Colors.white,
                                      size: 15.h,
                                    ),
                                    SizedBox(
                                      width: 10.h,
                                    ),
                                    Text(
                                      ditem.name!,
                                      style: TextStyle(
                                          color: Colors.white, fontSize: 15.h),
                                    ),
                                  ],
                                )),
                          ))
                      .toList()),
            )
          ],
        ),
      ),
      body: Stack(children: [
        // 背景
        Positioned(
            child: SizedBox(
          width: double.infinity,
          height: double.infinity,
          child: Image.asset(
            "assets/images/mahjong/background/index_bamboo_leaf.jpg",
            fit: BoxFit.fill,
          ),
        )),
        //第二部分 第二层 气泡

        //第三部分 高斯模糊
        //buildBlureWidget(),
        // 底部 透明背景条
        Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: ClipPath(
              //路径裁切组件
              clipper: PathClipper((size) {
                var path = Path();
                path.lineTo(20.h, 0);
                path.lineTo(0, size.height);
                path.lineTo(size.width, size.height);
                path.lineTo(size.width - 20.h, 0);
                return path;
              }),
              child: Container(
                alignment: Alignment.centerRight,
                height: 50.h,
                width: ScreenUtil().screenWidth,
                padding: EdgeInsets.symmetric(horizontal: 25.h),
                decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.bottomCenter,
                      end: Alignment.topCenter,
                      colors: [
                        const Color.fromARGB(187, 93, 93, 93),
                        const Color.fromARGB(124, 93, 93, 93),
                        Colors.grey.withOpacity(0.1)
                      ],
                    ),
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(10.h),
                        topRight: Radius.circular(10.h))),
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: _bottomItemList
                        .map((item) => Row(children: [
                              MaterialButton(
                                  onPressed: item.action,
                                  splashColor: Colors.green,
                                  child: Container(
                                    padding: EdgeInsets.symmetric(
                                        vertical: 2.h, horizontal: 20.w),
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        Image.asset(
                                          item.image ??
                                              "assets/images/system/history.png",
                                          height: 20.h,
                                          fit: BoxFit.cover,
                                        ),
                                        Text(
                                          item.name!,
                                          style: TextStyle(
                                              fontSize: 15.h,
                                              height: 1.0,
                                              color: Colors.white,
                                              fontFamily: AppContent.fontHyqmd),
                                        )
                                      ],
                                    ),
                                  ))
                            ]))
                        .toList()),
              ),
            )),

        /*   Positioned(
            top: 10.h,
            left: 60.w,
            child: Container(
              alignment: Alignment.center,
              height: 40.h,
              width: 200.w,
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(5.5),
                  child: ShaderMask(
                    shaderCallback: (Rect bounds) {
                      return LinearGradient(
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                          colors: [
                            Colors.transparent,
                            Colors.transparent,
                            Colors.orange,
                            Colors.black.withOpacity(0.2)
                          ],
                          stops: [
                            0,
                            .6,
                            .95,
                            1
                          ]).createShader(bounds);
                    },
                    blendMode: BlendMode.color,
                    child: Image.asset(
                      "assets/images/logo/logo.png",
                      fit: BoxFit.fill,
                    ),
                  )),
            )), */
        //  头像部分
        Consumer<UserEntityInfo>(builder: (buildContext, provider, child) {
          return Positioned(
            top: 60.h,
            bottom: 60.h,
            left: 60.w,
            child: Container(
                padding: EdgeInsets.all(10.w),
                height: double.infinity,
                width: 180.w,
                decoration: BoxDecoration(
                    color: Colors.grey.withOpacity(0.4),
                    borderRadius: BorderRadius.circular(10)),
                child: Stack(
                  children: [
                    BubbleWidget(
                      maxRadius: 5.w,
                    ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            InkWell(
                              child: Container(
                                width: 50.w,
                                height: 50.w,
                                decoration: BoxDecoration(
                                  boxShadow: [
                                    BoxShadow(
                                      color: Colors.black.withOpacity(0.2),
                                      blurRadius: 10.0,
                                      spreadRadius: 2.0,
                                      offset: const Offset(2.0, 2.0),
                                    ),
                                  ],
                                ),
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(5.w),
                                  child: MahjongCommon.headerImage(
                                      provider.sysUser.portraitUrl,
                                      width: 50.h,
                                      height: 50.h),
                                ),
                              ),
                              onTap: () async {
                                /* showDialog<Null>(
                                    context: context,
                                    barrierDismissible: false,
                                    builder: (BuildContext context) {
                                      return UserInfoDialog(
                                          title: 'title',
                                          description: 'description');
                                    }); */
                              },
                            ),
                            Expanded(
                                child: Text(
                              provider.sysUser.username!,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  /*  color: Colors.black, */
                                  fontSize: 20.w,
                                  foreground: Paint()
                                    ..style = PaintingStyle.stroke
                                    ..strokeWidth = 1
                                    ..color = Colors.white,
                                  fontWeight: FontWeight.bold),
                            ))
                          ],
                        ),
                        SizedBox(
                            width: 160.w,
                            height: 50.w,
                            child: Stack(
                              children: [
                                ClipPath(
                                  //路径裁切组件
                                  clipper: PathClipper((size) {
                                    var path = Path();
                                    path.lineTo(0, 0);
                                    path.lineTo(0, size.height);
                                    path.lineTo(
                                        size.width * 2 / 3, size.height);
                                    path.lineTo(size.width, 0);
                                    return path;
                                  }), //路径
                                  child: SizedBox(
                                    width: 90.w,
                                    child: MaterialButton(
                                        color: Colors.green,
                                        shape: RoundedRectangleBorder(
                                          //边框颜色
                                          side: const BorderSide(
                                            color: Colors.white,
                                            width: 1,
                                          ),
                                          //边框圆角
                                          borderRadius: BorderRadius.all(
                                            Radius.circular(15.r),
                                          ),
                                        ),
                                        onPressed: () {
                                          CustomerDialog.showGamingDialog(
                                              (cancelFunc) => CreateHomeDialog(
                                                  close: cancelFunc,
                                                  title: 'title',
                                                  description: 'description'));
                                        },
                                        child: Align(
                                          alignment: const Alignment(-0.5, 0),
                                          child: Text(
                                            " 创建\n房间",
                                            maxLines: 2,
                                            style: TextStyle(
                                                fontSize: 15.w,
                                                fontWeight: FontWeight.w900,
                                                height: 1.0,
                                                fontFamily:
                                                    AppContent.fontHyqmd,
                                                color: Colors.white),
                                          ),
                                        )),
                                  ),
                                ),
                                Align(
                                  alignment: Alignment.centerRight,
                                  child: ClipPath(
                                    //路径裁切组件
                                    clipper: PathClipper((size) {
                                      var path = Path();
                                      path.lineTo(size.width * 1 / 3, 0);
                                      path.lineTo(0, size.height);
                                      path.lineTo(size.width, size.height);
                                      path.lineTo(size.width, 0);
                                      return path;
                                    }), //路径
                                    child: SizedBox(
                                      width: 90.w,
                                      child: MaterialButton(
                                          color: Colors.orange,
                                          shape: RoundedRectangleBorder(
                                            //边框颜色
                                            side: const BorderSide(
                                              color: Colors.white,
                                              width: 1,
                                            ),
                                            //边框圆角
                                            borderRadius: BorderRadius.all(
                                              Radius.circular(15.r),
                                            ),
                                          ),
                                          onPressed: () {
                                            CustomerDialog.showGamingDialog(
                                              (cancel) => AddHomeDialog(
                                                  cancelFunc: cancel,
                                                  callback: (roomCode) {
                                                    Http.getInstance().request<
                                                            Restful>(
                                                        ApiRouter.addRoom,
                                                        type: RequestEnum.POST,
                                                        loadingMsg: "查找房间中...",
                                                        showLoading: true,
                                                        responseType:
                                                            ResponseType.json,
                                                        showErrorMsg: true,
                                                        data: {
                                                          "roomCode": roomCode
                                                        }, success: (result) {
                                                      cancel();
                                                      Map roomInfo =
                                                          result.body as Map;
                                                      InsertHome.addHome(
                                                          context,
                                                          roomInfo["type"],
                                                          roomCode);
                                                    }, error: (result) {});
                                                  }),
                                            );
                                          },
                                          child: Align(
                                            alignment: const Alignment(0.5, 0),
                                            child: Text(
                                              " 加入\n房间",
                                              maxLines: 2,
                                              //overflow: TextOverflow.ellipsis,
                                              style: TextStyle(
                                                  fontSize: 15.w,
                                                  fontWeight: FontWeight.w900,
                                                  height: 1.0,
                                                  fontFamily:
                                                      AppContent.fontHyqmd,
                                                  color: Colors.white),
                                            ),
                                          )),
                                    ),
                                  ),
                                ),
                              ],
                            )),
                      ],
                    ),
                  ],
                )),
          );
        }),
        // TIPS
        Positioned(
          top: 30.h,
          right: 60.w,
          child: Container(
            height: 30.h,
            width: 450.w,
            padding: EdgeInsets.symmetric(horizontal: 10.h),
            alignment: Alignment.centerLeft,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(7.5.h),
              color: Colors.grey.withOpacity(0.8),
            ),
            child: Row(
              children: [
                const Icon(
                  Icons.volume_up,
                  color: Colors.white,
                ),
                SizedBox(width: 10.w),
                Expanded(
                    child: SingleChildScrollView(
                        controller: _scrollController,
                        scrollDirection: Axis.horizontal,
                        child: Text(
                          "此平台仅用于学习交流,严禁赌博 ! ! ! 如有发现赌博行为将立即封号,并将信息发送给本地公安,请广大玩家遵守法律。",
                          maxLines: 1,
                          style:
                              TextStyle(color: Colors.white, fontSize: 14.sp),
                        )))
              ],
            ),
          ),
        ),
        // 广告位置
        Positioned(
          top: 60.h,
          bottom: 60.h,
          right: 60.w,
          child: Container(
            padding: EdgeInsets.all(10.h),
            height: double.infinity,
            width: 450.w,
            child: GridView(
              physics: const NeverScrollableScrollPhysics(),
              padding: const EdgeInsets.symmetric(vertical: 0),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 5, //每一行的列数
                mainAxisSpacing: 5, //主轴方向上的间距
                crossAxisSpacing: 10, //交叉轴轴方向上的间距
                childAspectRatio: 1,
              ),
              children: ["广", "告", "位", "置", "招", "租"]
                  .map((item) => Material(
                      color: Colors.white.withOpacity(0.3),
                      borderRadius: BorderRadius.circular(5.00),
                      child: Ink(
                          //设置背景 默认矩形
                          child: InkWell(
                              onTap: () {},
                              splashColor:
                                  const Color.fromARGB(255, 84, 241, 144),
                              child: Container(
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(5.00),
                                  border: Border.all(
                                      color: Colors.black.withOpacity(0.3)),
                                ),
                                child: Center(
                                    child: Text(
                                  item.toString(),
                                  style: TextStyle(
                                      color: Colors.orange,
                                      fontSize: ScreenUtil().setSp(30),
                                      fontWeight: FontWeight.bold),
                                )),
                              )))))
                  .toList(),
            ),
          ),
        )
      ]),
    );
  }

  Widget buildRoomWidget(
      String actionName, Color background, VoidCallback doAction) {
    return Container(
      /* padding: EdgeInsets.all(15.h), */
      decoration: BoxDecoration(
          color: background, borderRadius: BorderRadius.circular(5.h)),
      child: InkWell(
        onTap: doAction,
        child: Align(
          alignment: const Alignment(-0.3, 0),
          child: Text(
            actionName,
            maxLines: 2,
            //overflow: TextOverflow.ellipsis,
            style: TextStyle(
                fontSize: 15.sp,
                fontWeight: FontWeight.w900,
                fontFamily: AppContent.fontHyqmd,
                color: Colors.white),
          ),
        ),
      ),
    );
  }
}

//第三部分 高斯模糊
Widget buildBlureWidget() {
  return BackdropFilter(
    filter: ImageFilter.blur(sigmaX: 0.3, sigmaY: 0.3),
    child: Container(
      color: Colors.white.withOpacity(0.1),
    ),
  );
}
